const app = getApp();
let timer = null;

Page({
    data: {
        page: 1,
        num: 1,
        resdata: {},
        resdata2: {},
        id: "",
        timestr: '',
        timer: null,
        searchText: '',
        show: false,
        showFilter: false,
        pageList: [], // 分页列表字段
        overview: {},
        pageIndex: 1,
        pageSize: 20, // 默认20条
        hasNext: true,
        mobile: '',
        proportion: '',
        type: '1',
        disabled: false,
        editItem: {},
        businessType: 0,
        sort_type: [0], // 1待确认，2待入住，3已入住，4已完成，5已取消
        arrTime: ['', '今天', '昨天', '本月', '上月'],
        query: {},
        timeType: 0,
    },
    onChange(event) {
        console.log(event.detail, 'vant组件传值')
        if (event.detail == 2) {
            this.setData({
                proportion: 0.7,
            });
        } else {
            this.setData({
                proportion: '',
            });
        }
        this.setData({
            type: event.detail,
        });
    },
    onShow() {
        // this.getcount()
    },
    onLoad(query) {
        app.getUrl(this)
        app.getSystem(this)
        this.setData({
            query: query,
            store_info: wx.getStorageSync("store_info"),
            page: 1,
            pageIndex: 1,
            hasNext: true, // 初次加载，总是调用分页接口
            sort_type: query.three ? [1, 2, 3] : [0],
            searchText: query.searchText || ''
        });
        this.resetPageIndex() // 重置分页
        this.init() // 重置之后，开始请求
        // const instance = this.selectComponent('.van-hairline--top-bottom')
        // console.log(instance, 123)
    },
    init() {
        const arr = [...this.data.sort_type]
        if (arr.length > 1 && arr.includes(0)) { // 多选时，排除掉全部选项
            const idx = arr.findIndex(item => item == 0)
            arr.splice(idx, 1)
        }
        const str = arr.join(',')
        this.data.hasNext && wx.request({
            url: app.siteInfo.siteroot_web,
            cachetime: "0",
            method: "GET",
            data: {
                c: "statistics",
                a: "promoteOrderMoneyList",
                user_id: wx.getStorageSync('userInfo').id || 5,
                type: this.data.query.userType,
                time_type: this.data.timeType,
                order_type: str,
                seller_name: this.data.searchText,
                page: this.data.pageIndex,
            },
            success: (resp) => {
                const res = resp.data
                console.log('res--', res)
                if (res.code == 0) { // 请求成功
                    this.setData({
                        pageList: [...this.data.pageList, ...res?.data?.data], // 分页数据需要拼接
                        hasNext: res?.data?.current_page != res?.data?.last_page,
                        pageIndex: res?.data?.current_page + 1,
                        overview: res?.data?.overview,
                    })
                    wx.stopPullDownRefresh() // 及时关闭loading动画
                } else { // 请求失败
                    wx.showToast({
                        icon: 'none',
                        title: res.msg,
                    })
                }
            }
        });
    },

    resetPageIndex() {
        this.setData({
            pageIndex: 1,
            hasNext: true,
            pageList: [],
        })
    },
    /**
     * @function 搜索输入框的change事件回调
     * @param {*} e 
     */
    onChangeSearch(e) {
        this.debounce(() => {
            this.setData({
                searchText: e.detail,
            });
            this.resetPageIndex()
            this.init()
        }, 800)
    },
    /**
     * @function 简易防抖函数
     * @param {*} cb 回调函数
     * @param {*} wait 延迟时间
     */
    debounce(cb, wait) {
        timer && clearTimeout(timer)
        timer = setTimeout(cb, wait);
    },




    /**
     * @function 跳转到订单详情
     * @param {*} e 
     */

    /**
     * @function 订单筛选
     * @param {*} t 
     */

    show() {
        // console.log(this.data.num)
        const instance = this.selectComponent('.child1') // 拿到子组件实例，不推荐
        console.log(instance.data.val) // 获取子组件property和data，用法一致
    },
    confirm(ev) { // 通过子组件emit反向传值，省略了遍历获取实例
        // console.log(ev.detail)
        // console.log(ev.currentTarget.dataset.setkey)
        this.setData({
            [ev.currentTarget.dataset.setkey]: ev.detail.age
        })
        console.log('页面值与组件值保持同步', this.data.num)
    },





    /**
     * 去新增页面
     */
    toNew(ev) {
        const item = ev.currentTarget.dataset.item
        wx.navigateTo({
            url: `/zh_jdgjb/pages/agents/bindHotel/bindHotel?salesmanId=${item.id}&monthType=1`,
        })
    },
    /**
     * 去新增页面
     */
    toBind(ev) {
        const item = ev.currentTarget.dataset.item
        wx.navigateTo({
            url: `/zh_jdgjb/pages/agents/bindHotel/bindHotel?salesmanId=${item.id}&monthType=2`,
        })
    },

    /**
     * 调整佣金比例
     */
    adjust(ev) {
        const item = ev.currentTarget.dataset.item

        this.setData({
            show: true,
            disabled: true,
            mobile: item.user_info.tel,
            proportion: item.proportion,
            type: item.type + '',
            editItem: item,
        })
    },

    onClose() {
        this.setData({
            show: false
        });
    },
    onCloseFilter() {
        this.setData({
            showFilter: false
        });
    },
    /**
     * 调整佣金比例
     */
    addSale() {
        this.setData({
            show: true,
            disabled: false,
            mobile: '',
            proportion: '',
            type: '1',
        })
    },
    hideSale() {
        this.setData({
            show: false
        })
    },

    /**
     * 筛选
     */
    doFilter() {
        this.setData({
            showFilter: true
        })
    },

    hitOne(ev) {
        const type = ev.currentTarget.dataset.type
        this.setData({
            businessType: type,
        })
    },

    sure() {
        this.setData({
            showFilter: false,
            timeType: this.data.businessType
        })
        this.resetPageIndex()
        this.init()
    },
    sumbit() {
        const type = this.data.type
        const mobile = this.data.mobile
        const proportion = this.data.proportion
        console.log(proportion, mobile)
        const flag = !mobile || !proportion
        if (flag) {
            wx.showToast({
                title: '请填写完整！',
                icon: 'none'
            })
            return
        }
        if (proportion >= 2) {
            wx.showToast({
                title: '佣金比例不能超过2%',
                icon: 'none'
            })
            return
        }
        this.data.disabled ? wx.request({
            url: `${app.siteInfo.siteroot_web}?c=agent&a=editSaleman`,
            cachetime: "0",
            method: "POST",
            data: {
                c: "agent",
                a: "addSaleman",
                user_id: wx.getStorageSync('userInfo').id,
                type,
                mobile,
                proportion,
                id: this.data.editItem.id,
            },
            success: (resp) => {
                const res = resp.data
                console.log('res--', res)
                if (res.code == 0) { // 请求成功
                    wx.showToast({
                        title: this.data.disabled ? '编辑成功！' : '添加成功！',
                    })
                    this.hideSale()
                    // this.resetPageIndex() // 重置分页
                    // this.init() // 重置之后，开始请求
                    this.setData({
                        pageIndex: 1,
                        hasNext: true,
                        pageList: [],
                    }, () => {
                        this.init() // 重置之后，开始请求
                    })
                } else { // 请求失败
                    wx.showToast({
                        icon: 'none',
                        title: res.msg,
                    })
                }
            }
        }) : wx.request({
            url: `${app.siteInfo.siteroot_web}?c=agent&a=addSaleman`,
            cachetime: "0",
            method: "POST",
            data: {
                c: "agent",
                a: "addSaleman",
                user_id: wx.getStorageSync('userInfo').id,
                type,
                mobile,
                proportion,
            },
            success: (resp) => {
                const res = resp.data
                console.log('res--', res)
                if (res.code == 0) { // 请求成功
                    wx.showToast({
                        title: '添加成功！',
                    })
                    this.hideSale()
                    this.resetPageIndex() // 重置分页
                    this.init() // 重置之后，开始请求
                } else { // 请求失败
                    wx.showToast({
                        icon: 'none',
                        title: res.msg,
                    })
                }
            }
        })
    },
    hitSort(ev) {
        const type = Number(ev.currentTarget.dataset.type)
        const arr = [...this.data.sort_type]
        if (type == 0 && !arr.includes(0)) {
            this.setData({
                sort_type: [0],
            })
            return
        }
        const idx = arr.findIndex(item => item == type)
        console.log(idx, 666)
        if (idx == -1) {
            arr.push(type)
        } else {
            arr.splice(idx, 1)
        }
        console.log(arr, 777)
        const idx2 = arr.findIndex(item => item == 0)
        console.log()
        if (idx2 != -1) {
            arr.splice(idx2, 1)
        }
        console.log(arr, 'after')
        this.setData({
            sort_type: arr,
        })
    },
    onClose2(event) {
        const {
            position,
            instance,
        } = event.detail;
        console.log(event)
        switch (position) {
            case 'left':
            case 'cell':
                instance.close();
                break;
            case 'right':
                // Dialog.confirm({
                //   message: '确定删除吗？',
                // }).then(() => {
                //   instance.close();
                // });
                wx.showModal({
                    title: '',
                    content: '确定删除吗？',
                    complete: (res) => {
                        if (res.cancel) {

                        }

                        if (res.confirm) {
                            instance.close();
                            wx.request({
                                url: app.siteInfo.siteroot_web,
                                cachetime: "0",
                                method: "GET",
                                data: {
                                    c: "agent",
                                    a: "delSaleman",
                                    user_id: wx.getStorageSync('userInfo').id,
                                    id: event.currentTarget.dataset.item.id,
                                },
                                success: (resp) => {
                                    const res = resp.data
                                    console.log('res--', res)
                                    if (res.code == 0) { // 请求成功
                                        wx.showToast({
                                            icon: 'none',
                                            title: '删除成功！',
                                        })
                                        this.resetPageIndex()
                                        this.init()
                                    } else { // 请求失败
                                        wx.showToast({
                                            icon: 'none',
                                            title: res.msg,
                                        })
                                    }
                                }
                            });
                        }
                    }
                })
                break;
        }
    },
    /**
     * @function 复制
     */
    copy(e) {
        wx.setClipboardData({
            data: e.currentTarget.dataset.content
        })
    },
    /**
     * @function 下拉刷新
     */
    onPullDownRefresh: function () {
        this.setData({
            sort_type: [0],
            timeType: 0,
            businessType: 0
        })
        this.resetPageIndex() // 重置分页
        this.init() // 重置之后，开始请求
    },

    /**
     * @function 上拉加载回调
     */
    onReachBottom() {
        this.init() // 加载下一页
        wx.stopPullDownRefresh()
    },
});